package services

import (
	"errors"
	"hft/Database/admin"
	"hft/Http/Models/dao"
	"hft/global"
	"hft/tools"
)

func (*Article) CreateGroup(claims tools.BaseClaims, group admin.ArticleType) (err error) {

	var account *admin.Account

	err = global.OC_DB.Scopes(dao.ParseAccountDao.Parse(claims, global.OC_DB)).First(&account).Error

	if err != nil {
		return errors.New("无该账号信息")
	}

	group.AccountId = account.ID

	res := global.OC_DB.Where("name = ? AND account_id = ?", group.Name, group.AccountId).Omit("id").FirstOrCreate(&group)

	if res.Error != nil {
		return errors.New("未知错误500")
	}

	if res.RowsAffected == 0 {
		return errors.New("该分类已存在")
	}

	return nil
}

func (*Article) EditGroup(claims tools.BaseClaims, group admin.ArticleType) (err error) {

	var account *admin.Account

	var findGroup *admin.ArticleType

	err = global.OC_DB.Scopes(dao.ParseAccountDao.Parse(claims, global.OC_DB)).First(&account).Error

	if err != nil {
		return errors.New("无该账号信息")
	}

	err = global.OC_DB.First(&findGroup, group.ID).Error

	if err != nil {
		return errors.New("找不到该分组")
	}

	if findGroup.AccountId != account.ID {
		return errors.New("你无权修改该分组")
	}

	global.OC_DB.Model(&findGroup).Updates(map[string]interface{}{"name": group.Name, "sort": group.Sort})

	return nil
}

func (*Article) GetGroupList(claims tools.BaseClaims) (groups []*admin.ArticleType, err error) {

	var account *admin.Account

	err = global.OC_DB.Scopes(dao.ParseAccountDao.Parse(claims, global.OC_DB)).First(&account).Error

	if err != nil {
		return nil, errors.New("找不到该账号")
	}

	err = global.OC_DB.Order("sort desc").Omit("account_id").Find(&groups).Error

	if err != nil {
		return nil, errors.New("未知错误500")
	}

	return groups, nil
}

func (*Article) DeleteGroup(ids []int) (err error) {

	var groups []*admin.ArticleType

	global.OC_DB.Find(&groups, ids)

	global.OC_DB.Unscoped().Delete(&groups)

	return nil

}
